const { Sequelize, DataTypes } = require('sequelize');
const path = require('path');

const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: path.join(__dirname, 'fileinfo.db'),
  logging: false
});

const Files = sequelize.define('Files', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: DataTypes.STRING,
  path: DataTypes.STRING,
  size: DataTypes.INTEGER,
  buildVersion: DataTypes.STRING,
  buildVersionNo: DataTypes.STRING,
  buildUpdated: DataTypes.STRING,
  buildQRCodeURL: DataTypes.STRING,
  buildShortcutUrl: DataTypes.STRING,
  packageName: DataTypes.STRING,
  appName: DataTypes.STRING,
  iconUrl: DataTypes.STRING,
  qrPath: DataTypes.STRING,
  apkInfo: DataTypes.TEXT,
  createdAt: DataTypes.STRING
}, {
  timestamps: false,
  tableName: 'files'
});

async function syncFilesWithUploads() {
  try {
    const fs = require('fs');
    const path = require('path');
    const uploadsDir = path.join(__dirname, 'uploads');
    
    const allFiles = await Files.findAll();
    for (const file of allFiles) {
      const filePath = path.join(uploadsDir, file.path);
      if (!fs.existsSync(filePath)) {
        await file.destroy();
        console.log(`已删除不存在的文件记录: ${file.path}`);
        
        // 检查并删除空目录
        let currentDir = path.dirname(filePath);
        while (currentDir !== uploadsDir) {
          try {
            const filesInDir = fs.readdirSync(currentDir);
            if (filesInDir.length === 0) {
              fs.rmdirSync(currentDir);
              console.log(`已删除空目录: ${path.relative(uploadsDir, currentDir)}`);
              currentDir = path.dirname(currentDir);
            } else {
              break;
            }
          } catch (err) {
            console.error(`删除目录失败: ${currentDir}`, err);
            break;
          }
        }
      }
    }
    console.log('数据库与uploads目录同步完成');
  } catch (error) {
    console.error('同步失败:', error);
  }
}

async function initialize() {
  try {
    await sequelize.authenticate();
    await Files.sync();
    console.log('数据库连接成功');
    syncFilesWithUploads();
  } catch (error) {
    console.error('数据库连接失败:', error);
  }
}

initialize();

module.exports = {
  Files
};